<?php

namespace addons\facrm\controller\general;

use app\admin\model\Admin;
use addons\facrm\library\BackendApi;
use app\admin\model\AuthGroup;
use fast\Random;
use think\Validate;

/**
 * 个人配置
 * @icon fa fa-user
 */
class Profile extends BackendApi
{

    protected $noNeedRight = ['getInfo'];
    /**
     * 更新个人信息
     * @ApiMethod (POST修改)
     * @ApiParams(name="email", type="string", required=false, description="邮箱")
     * @ApiParams(name="nickname", type="string", required=false, description="昵称")
     * @ApiParams(name="password", type="string", required=false, description="密码")
     * @ApiParams(name="avatar", type="string", required=false, description="头像")
     */
    public function update()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post();
            $params = array_filter(array_intersect_key(
                $params,
                array_flip(array('email', 'nickname', 'password', 'avatar'))
            ));
            if (!$params)
            if (!Validate::is($params['email'], "email")) {
                $this->error(__("Please input correct email"));
            }
            if (isset($params['password'])) {
                if (!Validate::is($params['password'], "/^[\S]{6,16}$/")) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            $exist = Admin::where('email', $params['email'])->where('id', '<>', $this->auth->id)->find();
            if ($exist) {
                $this->error(__("Email already exists"));
            }
            if ($params) {
                $admin = Admin::get($this->auth->id);
                $admin->save($params);
                $this->success();
            }
            $this->error();
        }
        $this->error(__("请求有误"));
    }

    /**
     * 获取个人信息
     */
    public function getInfo(){

        $admin=$this->auth->getAdmin();
        $admin->hidden(['password','salt','token']);
        $groups = $this->auth->getGroups();



        $admin->avatar=cdnurl($admin->avatar,true);
        $admin=$admin->toArray();
        //获取是否有合同列表收款列表权限
        $admin['contract']=$this->auth->check('facrm/contract/index')?1:0;
        $admin['receivables']=$this->auth->check('facrm/contract/receivables')?1:0;
        foreach ($groups as $row) {
            $temp=array();
            $temp['id']=$row['id'];
            $temp['name']=__($row['name']);
            $admin['groups'][]=$temp;
        }

        $this->success('',$admin);
    }
}
